package chapter14.web;

import java.util.*;

import chapter14.core.*;

import chapter14.domain.*;

import chapter14.manager.*;

import com.softwarementors.extjs.djn.config.annotations.DirectFormPostMethod;
import com.softwarementors.extjs.djn.config.annotations.DirectMethod;

import org.apache.commons.fileupload.FileItem;


public class UserAction extends SecurityAction<User> {
    private UserManager userManager;
    private MenuManager menuManager;
    private RoleManager roleManager;

    @Override
    protected UserManager getEntityDao() {
        return userManager;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public void setMenuManager(MenuManager menuManager) {
        this.menuManager = menuManager;
    }

    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }

    @DirectFormPostMethod
    public Result checkLogin(Map<String, String> formParameters, Map<String, FileItem> fileFields) {
        String username = formParameters.get("username");
        String password = formParameters.get("password");
        String captcha = formParameters.get("captcha");

        String vcode = (String) this.getSessionValue("vcode");

        if ((vcode == null) || (!vcode.equals(captcha))) {
            return new Result(false, "验证码错误！");
        }

        if (username != null) {
            username = username.trim();
        }

        User user = userManager.findUniqueBy("name", username);

        if ((user == null) || (!user.getPassword().equals(password))) {
            return new Result(false, "用户名或密码错误！");
        }

        this.setSessionValue("user", user);

        return new Result("ok");
    }

    @DirectFormPostMethod
    public Result changePassword(Map<String, String> formParameters,
        Map<String, FileItem> fileFields) {
        User user = (User) this.getSessionValue("user");

        if (user == null) {
            return new Result(false, "请先登录");
        }

        String oldPassword = formParameters.get("oldPassword");
        String newPassword = formParameters.get("newPassword");
        String confirmPassword = formParameters.get("confirmPassword");

        if (this.isEmpty(oldPassword) || this.isEmpty(newPassword)
                || this.isEmpty(confirmPassword)) {
            return new Result(false, "请填写信息");
        }

        if (!newPassword.equals(confirmPassword)) {
            return new Result(false, "填写的两次密码不相同");
        }

        if (!user.getPassword().equals(oldPassword)) {
            return new Result(false, "旧密码不正确");
        }

        user = userManager.get(user.getId());
        user.setPassword(newPassword);
        userManager.save(user);
        this.setSessionValue("user", user);

        return new Result("密码修改成功");
    }

    @DirectMethod
    public Result getMenus() throws Exception {
        User user = (User) this.getSessionValue("user");
        String hql = "select distinct m.parent from Menu m left join m.roles r left join r.users u where u.id=?";
        List<Menu> list = menuManager.find(hql, user.getId());

        return new Result(list);
    }

    @DirectMethod
    @Override
    public Object list() throws Exception {
        if (!this.check("User")) {
            return this.failure();
        }

        return super.list();
    }

    @DirectFormPostMethod
    @Override
    public Object save(Map<String, String> param,
        Map<String, FileItem> files) throws Exception {
        if (!this.check("User")) {
            return this.failure();
        }

        return super.save(param, files);
    }

    @Override
    protected void beforeCreate(User entity, Map<String, String> param) {
        entity.setCreateDate(new Date());
    }

    @Override
    protected void beforeUpdate(User entity, Map<String, String> param) {
        if (param.get("password").equals("")) {
            param.remove("password");
        }
    }

    @Override
    protected void beforeSave(User entity, Map<String, String> param)
        throws Exception {
        super.beforeSave(entity, param);

        entity.getRoles().clear();

        String roleList = param.get("roleList");

        for (String str : roleList.split(",")) {
            try {
                long roleId = Long.parseLong(str);
                Role role = roleManager.get(roleId);
                entity.getRoles().add(role);
            } catch (Exception ex) {
                System.err.println(ex);
            }
        }
    }

    @DirectMethod
    @Override
    public Object remove(String ids) throws Exception {
        if (!this.check("User")) {
            return this.failure();
        }

        return super.remove(ids);
    }
}
